// UserController.java
package com.wms.controller;

import com.wms.common.Result;
import com.wms.entity.User;
import com.wms.service.UserService;
import com.wms.security.EncryptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private EncryptionService encryptionService; // 注入 EncryptionService

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        try {
            // 检查账号是否已存在
            if (userService.findByNo(user.getNo()) != null) {
                return Result.fail("账号已存在");
            }
            // 注册用户
            userService.register(user);
            return Result.suc("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("注册失败");
        }
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        try {
            User existingUser = userService.findByNo(user.getNo());
            if (existingUser != null) {
                // 解密数据库中存储的密码
                String decryptedPassword = encryptionService.decrypt(existingUser.getPassword());
                // 比较解密后的密码与用户输入的密码
                if (decryptedPassword.equals(user.getPassword())) {
                    // 生成 token
                    String token = userService.generateToken(existingUser);
                    return Result.suc("登录成功", token);
                }
            }
            return Result.fail("用户名或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("登录失败");
        }
    }
}
